package com.lottery.ruok.lottrey.utils

import android.Manifest
import android.app.Activity
import android.location.Location
import android.util.Log
import com.google.gson.Gson
import com.lottery.ruok.lottrey.bean.Payload
import com.lottery.ruok.lottrey.bean.SlackTextInfo
import com.lottery.ruok.lottrey.userInfo.UserInfo
import com.tbruyelle.rxpermissions2.RxPermissions
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import utils.Utils
import java.io.IOException
import java.io.Serializable
import java.util.*
import java.util.concurrent.TimeUnit

/**
 *
 * 作者：xuyf
 *
 * 创建日期：2018/8/23$
 *
 * 描述：
 *
 */
class PostSlackUtils constructor(context: Activity,ips:ArrayList<String>) {
    var mActivity:Activity
    var mIps:ArrayList<String>
    init {
        mActivity = context
        mIps = ips
    }
    val location: Location? by lazy { requestPermissions(context) }
    fun doPost() {
        val spec = ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_1)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
                        CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build()

        val logging = HttpLoggingInterceptor()
        logging.level = HttpLoggingInterceptor.Level.BODY//改为简单模式，可以随时打开

        var payload = Payload(
                "#ip上报",
                "Android",
                "${SlackTextInfo(
                        "经度：${location?.longitude}\n" +
                                "纬度：${location?.latitude}"
                        ,UserInfo.getToken(),mIps,Utils.getNetworkType(mActivity))}",
                ":ghost:"
        )
        val gson = Gson()
        val toJson = gson.toJson(payload)
        val requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), toJson)
        val okHttpClient = OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .connectionSpecs(Collections.singletonList(spec))
                .addInterceptor { chain: Interceptor.Chain? ->
                    val request = chain?.request()?.newBuilder()?.addHeader("Content-Type", "application/x-www-form-urlencoded")?.addHeader("Accept", "text/plain")?.addHeader("Content-length", requestBody.contentLength().toString())!!.build()
                    chain!!.proceed(request)
                }
                .build()


        Log.i("MAIN", toJson)


        val request = Request.Builder()
                .url("https://hooks.slack.com/services/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")//请求的url
                .post(requestBody)
                .build()
        //创建/Call
        val call = okHttpClient.newCall(request)
        //加入队列 异步操作
        call.enqueue(object : Callback {
            //请求错误回调方法
            override fun onFailure(call: Call, e: IOException) {
                Log.d("MAIN", "连接失败")
                e.printStackTrace()
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                Log.d("MAIN", "连接失败$response.body()!!.string()")
            }
        })
    }


    private fun requestPermissions(activity: Activity): Location? {
        if (activity == null) return null
        if (activity.isDestroyed) return null
        var location: Location? = null
        val rxPermission = RxPermissions(activity)
        rxPermission
                .requestEach(Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe { permission ->
                    if (permission.granted) {
                        // 用户已经同意该权限
                        location = LocationUtils.initLocation(activity)
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        location = null

                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        location = null

                    }
                }
        return location
    }
}